package com.example.wuyeguanli.activity;

import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.example.wuyeguanli.R;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;

@RunWith(AndroidJUnit4.class)
public class AnnouncementActivityTest {

    @Test
    public void testAnnouncementList_IsDisplayedAndContainsCorrectData() {
        // 1. 启动公告Activity
        ActivityScenario.launch(AnnouncementActivity.class);

        // 2. 验证RecyclerView是可见的
        onView(withId(R.id.recyclerView)).check(matches(isDisplayed()));

        // 3. 验证第一条公告的内容是否正确
        onView(withId(R.id.recyclerView))
                // 滚动到第0个位置
                .perform(RecyclerViewActions.scrollToPosition(0));

        // 使用自定义Matcher定位到第0个item，并检查其子视图
        onView(new RecyclerViewMatcher(R.id.recyclerView).atPosition(0))
                .check(matches(allOf(
                        hasDescendant(withText("热烈欢迎总书记莅临社区")),
                        hasDescendant(withText("2025/6/4")),
                        hasDescendant(withText("总书记来到社区进行观光与指导工作"))
                )));

        // 4. 验证最后一条公告的内容是否正确
        onView(withId(R.id.recyclerView))
                // 滚动到第4个位置 (总共5条，索引是0-4)
                .perform(RecyclerViewActions.scrollToPosition(4));

        onView(new RecyclerViewMatcher(R.id.recyclerView).atPosition(4))
                .check(matches(hasDescendant(withText("居委会成员选举结果公示"))));

        // 5. （可选）验证返回按钮可以点击
        onView(withId(R.id.btn_back)).perform(click());
        // 由于点击返回会销毁Activity，这里很难做强断言，主要验证点击不崩溃即可。
    }

    @Test
    public void testRecyclerView_HasCorrectItemCount() {
        ActivityScenario.launch(AnnouncementActivity.class);

        // 验证RecyclerView中的项目总数是否为5
        onView(withId(R.id.recyclerView)).check(new RecyclerViewItemCountAssertion(5));
    }
}